<template>
    <view class="container">
        <!-- 顶部标题栏 -->
        <view class="header">
            <text class="title">第 {{ roundNumber }} 局结算</text>
            <view class="divider"></view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
            <uni-load-more status="loading"></uni-load-more>
        </view>
        
        <!-- 错误提示 -->
        <view v-if="error" class="error-state">
            <image src="@/static/logo.png" class="error-icon"></image>
            <text class="error-text">{{ error }}</text>
            <button class="retry-button" @click="initData">重试</button>
        </view>

        <!-- 主要内容区域 -->
        <view v-if="!loading && !error" class="content">
            <!-- 玩家结算卡片列表 -->
            <view class="player-cards">
                <view v-for="(player, index) in players" :key="player.userId" class="player-card">
                    <!-- 玩家头像和信息 -->
                    <view class="player-info">
                        <image :src="player.avatar || defaultAvatar" class="avatar"></image>
                        <text class="player-name">{{ player.nickname }}</text>
                        <text class="role-tag" v-if="player.isWinner">赢家</text>
                    </view>
                    
                    <!-- 分数输入区域 -->
                    <view class="score-section">
                        <text class="score-label">得分:</text>
                        <input 
                            type="number" 
                            v-model="player.score" 
                            placeholder="0"
                            class="score-input"
							@focus="clearIfDefault(player)"
							@blur="restoreDefault(player)"
                            @input="validateScore(player)"
                            :disabled="player.userId !== currentUserId || isSubmitting" 
                            :class="{ 'disabled-input': player.userId !== currentUserId }"
                        />
                    </view>
                    
                    <!-- 赢家选择 -->
                    <view class="winner-section" v-if="player.userId === currentUserId || player.isWinner">
                        <text class="winner-label">赢家:</text>
                        <switch 
                            :checked="player.isWinner" 
                            @change="handleWinnerChange(player.userId, $event.detail.value)"
                            color="#07C160"
                            class="winner-switch"
                            :disabled="isSubmitting"
                        />
                    </view>
                </view>
            </view>
            
            <!-- 结算说明 -->
            <view class="settlement-info">
                <text class="info-text">结算规则：赢家获得所有非赢家支付的分数总和，非赢家支出与自身得分等额的分数</text>
            </view>
            
            <!-- 底部操作栏 -->
            <view class="action-bar">
                <button class="action-button secondary" @click="backbutton" :disabled="isSubmitting">
                    <text>取消</text>
                </button>
                
                <button 
                  class="action-button primary" 
                  @click="confirmbutton" 
                  :disabled="isSubmitting || !allScoresFilled || !hasWinner" 
                >
                  <template v-if="!isSubmitting">
                    <text v-if="allScoresFilled && hasWinner">确认结算</text>
                    <text v-else>请完成结算信息</text>
                  </template>
                  <text v-else>提交中...</text>
                </button>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onUnmounted, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useSocketStore } from '@/stores/modules/socketStore.js';

// 默认头像
const defaultAvatar = 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png';
// 状态管理实例
const socketStore = useSocketStore();
// 从 socketStore 中解构所需的响应式状态
const { connectionState, roomData } = storeToRefs(socketStore);
// 响应式数据
const loading = ref(true);         // 加载状态
const error = ref(null);           // 错误信息
const isSubmitting = ref(false);   // 提交状态
const roundNumber = ref(0);        // 当前回合数？
const players = ref([]);           // 玩家列表（结算数据）？
const roomId = ref('');            // 房间ID？
const currentUserId = ref('');     // 当前用户ID————缓存起来？直接从缓存取

/**
 * 初始化数据 - 从 socketStore.roomData 获取玩家信息（核心修正点）
 */
const initData = async () => {
  try {
    loading.value = true;
    error.value = null;
    
    // 1. 获取当前用户ID
    const userStr = uni.getStorageSync('user') || '{}';
    const user = JSON.parse(userStr);
    currentUserId.value = user.userinfo?.userid || '';
    
    // 2. 从 socketStore.roomData 获取当前房间数据
    const currentRoomData = roomData.value[roomId.value];
    if (!currentRoomData || !currentRoomData.members) {
      throw new Error('房间数据不存在，请重新进入房间');
    }
    
    // 3. 转换全局状态数据为结算页面所需格式————这里二次赋值  是否破坏了响应式?  roomdata更新play会更新吗  好像是会的 找下是在哪里跟新的  因为加载到新进房间的人的分数狂了   那是从用户列表中过来的？
    players.value = Object.values(currentRoomData.members).map(member => ({
      userId: member.user_id,       // 注意：与 socketStore 中成员数据的字段保持一致（原数据中是 user_id）
      nickname: member.nickname,    // 从全局成员数据获取
      avatar: member.avatar,        // 从全局成员数据获取
      score: "0",                   // 初始化分数
      isWinner: false               // 初始化赢家状态
    }));    
    
    // 4. 注册Socket事件监听
    registerSocketListeners();
	
  } catch (err) {
    error.value = err.message || '加载数据失败，请稍后重试';
    console.error('初始化数据出错:', err);
  } finally {
    loading.value = false;
  }
};

/**
 * 注册Socket事件监听
 */
const registerSocketListeners = () => {
  // 监听其他玩家的分数和赢家状态更新
  socketStore.on('score_updated', (data) => {
    if (data.room_id !== roomId.value || data.roundNumber !== roundNumber.value) return;
    
    const { user_id, score, isWinner } = data;
    const player = players.value.find(p => p.userId === user_id);
    
    if (player && user_id !== currentUserId.value) {
      player.score = score.toString();
      player.isWinner = isWinner;
    }
  });
  // 监听其他玩家的结算数据更新
  socketStore.on('roundpay_update', (data) => {
    if (data.room_id !== roomId.value || data.roundNumber !== roundNumber.value) return;
    // 更新其他玩家的数据，保留自己的数据不变
    players.value = players.value.map(player => {
      const remotePlayer = data.players.find(p => p.userId === player.userId);
      if (remotePlayer && player.userId !== currentUserId.value) {
        return {
          ...player,
          score: remotePlayer.score,
          isWinner: remotePlayer.isWinner
        };
      }
      return player;
    });
  });
  // 监听结算完成事件————给后端使用
  socketStore.on('settlement_completed', (data) => {
    if (true) {
    // if (data.room_id === roomId.value && data.roundNumber === roundNumber.value) {
      uni.showToast({ title: '本局结算已完成' });
      setTimeout(() => uni.navigateBack(), 1500);
    }
  });
};

/**
 * 页面加载时初始化
 */
onLoad((options) => {
  roomId.value = options.roomId;
  roundNumber.value = parseInt(options.roundNumber) || 0;
  
  // 检查Socket连接状态
  if (connectionState.value !== 'connected' || !socketStore.isConnectedToRoom(roomId.value)) {
    socketStore.connect(roomId.value).then(initData);
  } else {
    initData();
  }
  
  // 监听 socketStore 中房间成员变化
  // watch(() => roomData.value[roomId.value]?.members, (newMembers) => {
  //   if (newMembers && !isSubmitting.value) {
  //     // 保留已输入的分数和赢家状态
  //     const currentScores = players.value.reduce((acc, p) => {
  //       acc[p.userId] = { score: p.score, isWinner: p.isWinner };
  //       return acc;
  //     }, {});
      
  //     // 合并新的成员列表和已有分数
  //     players.value = Object.values(newMembers).map(member => ({
  //       userId: member.user_id,  // 注意字段一致性：user_id
  //       nickname: member.nickname,
  //       avatar: member.avatar,
  //       ...(currentScores[member.user_id] || { score: "0", isWinner: false })
  //     }));
  //   }
  // }, { deep: true });
});

/**
 * 分数输入验证与同步
 */
const validateScore = (player) => {
  // 输入验证
  player.score = player.score.replace(/[^\d]/g, '');
  if (!player.score) player.score = "0";
  const num = parseInt(player.score) || 0;
  if (num > 500) player.score = '500';
  // 同步到其他玩家
  // if (player.userId === currentUserId.value) {
  //   socketStore.emit('score_updated', {
  //     room_id: roomId.value,
  //     roundNumber: roundNumber.value,
  //     user_id: currentUserId.value,
  //     score: player.score,
  //     isWinner: player.isWinner
  //   });
    
  // }
};
const clearIfDefault = (player) => {
  if (player.score === "0") player.score = "";
};
const restoreDefault = (player) => {
  if (player.score === "") player.score = "0";
};


// 在分数或赢家状态变化时发送更新
const emitRoundpayUpdate = () => {
  socketStore.emit('roundpay_update', {
    room_id: roomId.value,
    roundNumber: roundNumber.value,
    players: players.value.map(p => ({
      userId: p.userId,
      score: p.score,
      isWinner: p.isWinner
    }))
  });
};
/**
 * 赢家状态改变与同步
 */
const handleWinnerChange = (userId, isWinner) => {
  if (userId !== currentUserId.value) return;
  
  if (isWinner) {
    players.value.forEach(p => p.isWinner = false);
  }
  
  const player = players.value.find(p => p.userId === userId);
  if (player) {
    player.isWinner = isWinner;
	// 新增：自动设置赢家分数为20
    if (isWinner) {
      player.score = "20";
    }
    // 广播状态变化
    // socketStore.emit('score_updated', {
    //   room_id: roomId.value,
    //   roundNumber: roundNumber.value,
    //   user_id: currentUserId.value,
    //   score: player.score,
    //   isWinner: isWinner
    // });
    
  }
};



/**
 * 计算属性：是否所有分数都已填写
 */
const allScoresFilled = computed(() => {
  return players.value.every(player => {
    const score = parseInt(player.score);
    return player.score !== '' && !isNaN(score) && score >= 0;
  });
});

/**
 * 计算属性：是否已选择赢家
 */
const hasWinner = computed(() => {
  return players.value.some(p => p.isWinner);
});

/**
 * 提交结算数据
 */
const confirmbutton = async () => {
  try {
    isSubmitting.value = true;
    console.log(players)
    if (!allScoresFilled.value) {
      uni.showToast({ title: '请填写所有玩家分数', icon: 'none' });
      return;
    }
    
    if (!hasWinner.value) {
      uni.showToast({ title: '请选择一个赢家', icon: 'none' });
      return;
    }
    
    // 准备提交数据
    const submitData = {
      roomId: roomId.value,
      roundNumber: roundNumber.value,
      players: players.value.map(p => ({
        userId: p.userId,
        score: parseInt(p.score),
        isWinner: p.isWinner
      }))
    };
    
    // 通过Socket提交结算数据
    // const result = await socketStore.submitSettlement(submitData);  
    // if (result.success) {
    //   uni.showToast({ title: '结算成功' });
    //   setTimeout(() => uni.navigateBack(), 1500);
    // } else {
    //   uni.showToast({ title: result.message || '提交失败', icon: 'none' });
    // }
	
	
	const res = await uni.request({
	      url: 'http://172.16.24.120:5000/mysqlroom/rounds/settle',
	      method: 'POST',
	      data: submitData
	    });
	if (res.statusCode === 200) {
	      uni.showToast({ title: '结算成功' });
	      setTimeout(() => uni.navigateBack(), 1500);
	} 
	else {
	    // throw new Error('提交分数失败');
		uni.showToast({
		    title: res.message || '提交分数失败',
		    icon: 'none'
		});
	}
	
	
	
	
	
	
  } catch (err) {
    console.error('结算提交失败:', err);
    uni.showToast({ title: err.message || '提交失败', icon: 'none' });
  } finally {
    isSubmitting.value = false;
  }
};

/**
 * 返回按钮处理
 */
const backbutton = () => {
  // uni.navigateBack();
  emitRoundpayUpdate();
};

/**
 * 组件卸载时清理
 */
onUnmounted(() => {
  socketStore.off('score_updated');
  socketStore.off('settlement_completed');
});

/**
 * 监听Socket连接状态变化
 */
watch(connectionState, (newState) => {
  if (newState === 'disconnected' && !loading.value && !error.value) {
    error.value = '连接已断开，请重试';
  }
});
</script>

<style scoped>
/* 全局容器样式 */
.container {
    padding: 0;
    background-color: #f8f8f8;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}
/* 头部样式 */
.header {
    padding: 20px 16px 12px;
    background-color: #ffffff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.title {
    font-size: 20px;
    font-weight: 600;
    color: #333;
    text-align: center;
}

.divider {
    height: 1px;
    background-color: #eee;
    margin-top: 12px;
}

/* 加载状态样式 */
.loading-state {
    padding: 40px 0;
    display: flex;
    justify-content: center;
}

/* 错误状态样式 */
.error-state {
    padding: 40px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.error-icon {
    width: 60px;
    height: 60px;
    margin-bottom: 16px;
}

.error-text {
    font-size: 16px;
    color: #ff4d4f;
    margin-bottom: 20px;
    text-align: center;
}

.retry-button {
    background-color: #1890ff;
    color: white;
    border: none;
    border-radius: 20px;
    padding: 8px 24px;
    font-size: 14px;
}

/* 主要内容区域 */
.content {
    flex: 1;
    padding: 16px;
    display: flex;
    flex-direction: column;
}

/* 结算说明 */
.settlement-info {
    padding: 12px 16px;
    background-color: #fff8e6;
    border-radius: 8px;
    margin: 10px 0;
}

.info-text {
    font-size: 14px;
    color: #e6a23c;
    line-height: 1.5;
}

/* 玩家卡片列表 */
.player-cards {
    flex: 1;
}

.player-card {
    background-color: #fff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.player-info {
    display: flex;
    align-items: center;
    flex: 1;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
}

.player-name {
    font-size: 16px;
    color: #333;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100px;
}

.role-tag {
    background-color: #07C160;
    color: white;
    font-size: 12px;
    padding: 2px 8px;
    border-radius: 12px;
    margin-left: 8px;
}

/* 分数输入区域 */
.score-section {
    display: flex;
    align-items: center;
    margin: 0 16px;
}

.score-label {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
}

.score-input {
    width: 80px;
    height: 36px;
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 0 10px;
    text-align: center;
    font-size: 16px;
    color: #333;
    background-color: #f9f9f9;
}

/* 赢家选择区域 */
.winner-section {
    display: flex;
    align-items: center;
}

.winner-label {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
}

.winner-switch {
    transform: scale(0.8);
}

/* 底部操作栏 */
.action-bar {
    display: flex;
    justify-content: space-between;
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #eee;
    position: sticky;
    bottom: 0;
}

.action-button {
    flex: 1;
    height: 48px;
    border-radius: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s;
}

.action-button.secondary {
    background-color: #f5f5f5;
    color: #666;
    margin-right: 12px;
}

.action-button.secondary:active {
    background-color: #e5e5e5;
}

.action-button.primary {
    background-color: #07C160;
    color: white;
}

.action-button.primary:disabled {
    background-color: #a0d7b8;
    opacity: 0.7;
}

.action-button.primary:active:not(:disabled) {
    background-color: #05a14e;
}

/* 非当前用户的输入框样式 */
.disabled-input {
  background-color: #f0f0f0;
  color: #999;
  cursor: not-allowed;
}
</style>
